package com.ruoyi.web.controller.Task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.Constants;
import com.ruoyi.system.entity.GlPeople;
import com.ruoyi.system.entity.NucleicAcid;
import com.ruoyi.system.entity.VitalSigns;
import com.ruoyi.system.entity.WarningRule;
import com.ruoyi.system.mapper.GlPeopleMapper;
import com.ruoyi.system.service.GlPeopleService;
import com.ruoyi.system.service.NucleicAcidService;
import com.ruoyi.system.service.VitalSignsService;
import com.ruoyi.system.service.WarningRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName JobTask.java
 * @Description TODO
 * @createTime 2023年11月28日 11:57:00
 */
@Component("jobTask")
public class JobTask {

    @Resource
    private JavaMailSender javaMailSender;

    @Autowired
    private GlPeopleService glPeopleService;


    @Autowired
    private VitalSignsService vitalSignsService;

    @Autowired
    private NucleicAcidService nucleicAcidService;

    @Autowired
    private WarningRuleService warningRuleService;


    /**
     * 邮箱号
     */
    @Value("${spring.mail.username}")
    private String email;

    public void test(String mail, String code) {
        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("注册验证码");
        message.setText("你的验证码是" + code + "有效期是" + Constants.CAPTCHA_EXPIRATION + "分钟" + "," + "请不要告诉他人哦！");
        message.setFrom(email);
        message.setTo(mail);
        javaMailSender.send(message);
    }

    /**
     * 预警定时任务
     */
    public void warning(String mail, Long id) {

        LocalDate now = LocalDate.now();
        LocalDateTime startOfDay = now.atStartOfDay();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedStartOfDay = startOfDay.format(formatter);
        System.out.println(formattedStartOfDay);

        System.out.println("预警定时任务" + formattedStartOfDay);
        //当天测试温度  当天核酸检测
        LambdaQueryWrapper<VitalSigns> vitalSignsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //时间大于formattedStartOfDay
        vitalSignsLambdaQueryWrapper.gt(VitalSigns::getMeasurementDate, formattedStartOfDay);

        List<VitalSigns> vitalSignsList = vitalSignsService.list(vitalSignsLambdaQueryWrapper);
        //通过userId去重
        ArrayList<VitalSigns> vitalSigns = vitalSignsList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() ->
                                new TreeSet<>(Comparator.comparing(VitalSigns::getUserId))), ArrayList::new));

        ArrayList<Long> longs = new ArrayList<>();
        //通过id查找预警规则
        WarningRule warningRule = warningRuleService.getById(id);
        if (warningRule.getState() == 1) {
            throw new RuntimeException("预警规则已经关闭");
        }

        for (VitalSigns vitalSign : vitalSigns) {
            //体温
            if (Double.parseDouble(vitalSign.getTemperature()) > Double.parseDouble(warningRule.getTemperatureS())
                    || Double.parseDouble(vitalSign.getTemperature()) < Double.parseDouble(warningRule.getTemperatureDownX())
                    && Double.parseDouble(vitalSign.getBloodPressure()) > Double.parseDouble(warningRule.getBloodPressureS())
                    || Double.parseDouble(vitalSign.getBloodPressure()) < Double.parseDouble(warningRule.getBloodPressureX())
                    && vitalSign.getRespiratoryRate() > Integer.parseInt(warningRule.getRespiratoryRateS())
                    || vitalSign.getRespiratoryRate() < Integer.parseInt(warningRule.getRespiratoryRateX())
                    && Integer.parseInt(vitalSign.getOxygenSaturation()) > Integer.parseInt(warningRule.getOxygenSaturationS())
                    || Integer.parseInt(vitalSign.getOxygenSaturation()) < Integer.parseInt(warningRule.getOxygenSaturationX())

            ) {
                longs.add(vitalSign.getUserId());
            }
        }

        ArrayList<Long> userIds = new ArrayList<>();
        LambdaQueryWrapper<NucleicAcid> nucleicAcidLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //时间大于formattedStartOfDay
        nucleicAcidLambdaQueryWrapper.gt(NucleicAcid::getDetectionTime, formattedStartOfDay);
        nucleicAcidLambdaQueryWrapper.eq(NucleicAcid::getDetectionResult, "1");
        List<NucleicAcid> nucleicAcidList = nucleicAcidService.list(nucleicAcidLambdaQueryWrapper);
        for (NucleicAcid nucleicAcid : nucleicAcidList) {
            for (Long aLong : longs) {
                if (nucleicAcid.getUserId().equals(aLong)) {
                    userIds.add(aLong);
                }
            }
        }
        if (userIds.size() == 0) {
            // 发送邮件
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("异常人员预警通知");
            message.setText("今天隔离点无人员超过制定预警范围！");
            message.setFrom(email);
            message.setTo(mail);
            javaMailSender.send(message);
        }

        String userName = "";
        for (Long userId : userIds) {
            GlPeople glPeople = glPeopleService.getById(userId);
            if (userName.equals("")){
                userName = glPeople.getUserName();
            }
            userName = userName + "," + glPeople.getUserName();
        }
        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("异常人员预警通知");
        message.setText("隔离点人员" + userName + "超过制定预警范围,请及时登录预警平台进行查看！");
        message.setFrom(email);
        message.setTo(mail);
        javaMailSender.send(message);
        System.out.println("预警定时任务");
    }


}
